import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/ble/protocol_data_util.dart';
import 'package:ty_smart_watch/common/function_id.dart';
import 'package:ty_smart_watch/page/watch_setting_page/controller/watch_setting_controller.dart';
import 'package:ty_smart_watch/utils/Log.dart';

class WatchTimeRangeSettingPage extends StatefulWidget {
  const WatchTimeRangeSettingPage({super.key});

  @override
  State<WatchTimeRangeSettingPage> createState() => _WatchTimeRangeSettingPageState();
}

class _WatchTimeRangeSettingPageState extends State<WatchTimeRangeSettingPage> {
  int _functionId = 0; //功能id
  String _mac = ""; //设备地址
  String _title = ""; //页面标题
  // bool _switchValue = false; //开关

  final _trailingStyle = const TextStyle(color: Color(0xFF3075E9));
  final _titleStyle = const TextStyle(fontSize: 18);
  final _confirmColor = const Color(0xFF3075E9);
  final _unConfirmColor = const Color(0xFF80A3DF);

  final _controller = Get.put(WatchSettingController());

  @override
  void initState() {
    super.initState();
    _functionId = Get.arguments["id"];
    _mac = Get.arguments["mac"];
    Log.d("页面收到的数据：$_functionId > $_title > $_mac");
    _controller.getBleData(_mac, _functionId);
    _initStyle(_functionId);
  }

  @override
  Widget build(BuildContext context) {
    ever(
      _controller.needClosePage,
      (need) => {
        Log.d("need close page: $need"),
        if (need == 2) {Get.back()}
      },
    );
    return Scaffold(
      appBar: AppBar(
        title: Text(_title),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Column(
        children: [
          //开关
          Obx(
            () => SwitchListTile(
              dense: true,
              inactiveThumbColor: _unConfirmColor,
              inactiveTrackColor: _unConfirmColor.withAlpha(88),
              activeColor: _confirmColor,
              activeTrackColor: _confirmColor.withAlpha(88),
              title: Text("开关", style: _titleStyle),
              onChanged: (bool value) {
                Log.d("switch value :  $value");
                var temp = _controller.timeRangeBean.value;
                Log.d("timeRangeBean switch  value :  ${temp.isSwitch}");
                temp.isSwitch = value;
                _controller.updateTimeRangeBean(temp);
              },
              value: _controller.timeRangeBean.value.isSwitch,
            ),
          ),
          //todo RadioGroup

          Obx(
            () => Visibility(
              visible: _controller.timeRangeBean.value.isSwitch,
              child: Column(
                children: [
                  //开始时间
                  ListTile(
                    title: Text("开始时间", style: _titleStyle),
                    trailing: Obx(
                      () => Text(
                        "${_controller.timeRangeBean.value.startHour}:${_controller.timeRangeBean.value.startMinute}",
                        style: _trailingStyle,
                      ),
                    ),
                    onTap: () {
                      _clickStartTime(_controller.timeRangeBean.value.startHour,
                          _controller.timeRangeBean.value.startMinute);
                    },
                  ),

                  //结束时间
                  ListTile(
                    title: Text("结束时间", style: _titleStyle),
                    trailing: Obx(
                      () => Text(
                        "${_controller.timeRangeBean.value.endHour}:${_controller.timeRangeBean.value.endMinute}",
                        style: _trailingStyle,
                      ),
                    ),
                    onTap: () {
                      _clickEndTime(_controller.timeRangeBean.value.endHour,
                          _controller.timeRangeBean.value.endMinute);
                    },
                  ),

                  //间隔时间
                  ListTile(
                    title: Text("间隔时间", style: _titleStyle),
                    trailing: Obx(
                      () => Text(
                        "${_controller.timeRangeBean.value.duration}分钟",
                        style: _trailingStyle,
                      ),
                    ),
                    onTap: () async {
                      _clickDurationTime();
                    },
                  ),
                ],
              ),
            ),
          ),

          //占位
          const Expanded(child: SizedBox()),
          //确认按钮
          Container(
            width: double.infinity,
            height: 46,
            margin: const EdgeInsets.symmetric(horizontal: 20),
            child: TextButton(
              onPressed: () {
                _confirm();
              },
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.blue),
                foregroundColor: MaterialStateProperty.all(Colors.white),
                shape: MaterialStateProperty.all(
                  const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(30)),
                  ),
                ),
              ),
              child: const Text('确认'),
            ),
          ),
          const SizedBox(height: 60),
        ],
      ),
    );
  }

  _initStyle(int functionId) {
    switch (functionId) {
      case HAND_BRIGHTEN_SCREEN:
        _title = "抬手亮屏设置";
        break;
      case DO_NOT_DISTURB:
        _title = "勿扰设置";
        break;
      case DRINK_REMIND:
        _title = "喝水提醒";
        break;
      case LONG_SIT:
        _title = "久坐提醒";
        break;
      case TIME_HEART:
        _title = "定时心率提醒";
        break;
      case TIMING_BODY_TEMPERATURE:
        _title = "定时体温设置";
        break;
      case MEDICINE_REMIND:
        _title = "吃药提醒";
        break;
      case MEDICINE_REMIND:
        _title = "生理期设置";
        break;
    }
  }

  // 使用示例
  void showInputDialog(BuildContext context) async {
    var result = await showDialog(
      context: context,
      builder: (BuildContext context) {
        return InputDialog();
      },
    );

    if (result != null) {
      // 处理输入的文本
      print('Entered text: $result');
    }
  }

  _clickDurationTime() {
    // showInputDialog(context);
    TextEditingController textController = TextEditingController();
    var res = "";
    Get.defaultDialog(
      title: '时间间隔',
      content: Column(
        children: [
          Text("0~255分钟"),
          TextField(
            controller: textController,
            onChanged: (v) {},
            decoration: const InputDecoration(
                hintText: "请输入间隔时间(分钟)",
                hintStyle: TextStyle(
                  color: Color(0xFF969696),
                ),
                border: InputBorder.none),
            keyboardType: TextInputType.number,
            inputFormatters: [
              FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
            ],
            maxLines: 1,
          ),
        ],
      ),
      textConfirm: '确定',
      textCancel: '取消',
      onConfirm: () {
        // 用户点击确认按钮时执行的操作
        if (textController.text.isNotEmpty) {
          int mDuration = int.parse(textController.text);
          var temp = _controller.timeRangeBean.value;
          temp.duration = mDuration;
          _controller.updateTimeRangeBean(temp);
        }
        Get.back();
      },
      onCancel: () {
        // 用户点击取消按钮时执行的操作
      },
    );
  }

  _clickStartTime(int hour, int minute) {
    Pickers.showDatePicker(
      context,
      mode: DateMode.HM,
      selectDate: PDuration(hour: hour, minute: minute),
      onConfirm: (p) {
        Log.d('开始时间选择器：$p');
        var temp = _controller.timeRangeBean.value;
        temp.startHour = p.hour ?? 0;
        temp.startMinute = p.minute ?? 0;
        _controller.updateTimeRangeBean(temp);
      },
    );
  }

  _clickEndTime(int hour, int minute) {
    Pickers.showDatePicker(
      context,
      mode: DateMode.HM,
      selectDate: PDuration(hour: hour, minute: minute),
      onConfirm: (p) {
        Log.d('结束时间选择器：$p');
        var temp = _controller.timeRangeBean.value;
        temp.endHour = p.hour ?? 0;
        temp.endMinute = p.minute ?? 0;
        _controller.updateTimeRangeBean(temp);
      },
    );
  }

  /// 提交信息到手表
  _confirm() {
    //将数据传送给手表 write
    _controller.updateNeedClosePage(1);
    var mData = _makeDataForWatch();
    BleUtil.writeBleData(_mac, BleUtil.makeWriteData(functionId: _functionId, data: mData));
  }

  ///整合要提交的数据
  List<int> _makeDataForWatch() {
    List<int> result;
    switch (_functionId) {
      //"喝水提醒设置"
      case DRINK_REMIND:
      //"定时心率设置:
      case TIME_HEART:
      //"定时体温设置:
      case TIMING_BODY_TEMPERATURE:
      //"久坐提醒设置:
      case LONG_SIT:
        var temp = _controller.timeRangeBean.value;
        int resSwitch = (temp.isSwitch) ? 1 : 0;
        result = ProtocolDataUtil.instance!.commonTimeRange(resSwitch, temp.startHour,
            temp.startMinute, temp.endHour, temp.endMinute, temp.duration);
        break;
      default:
        result = [0];
    }
    return result;
  }
}

class InputDialog extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    TextEditingController _controller = TextEditingController();

    return AlertDialog(
      title: Text('Enter Text'),
      content: TextField(
        controller: _controller,
        decoration: InputDecoration(hintText: 'Enter text here'),
      ),
      actions: <Widget>[
        MaterialButton(
          onPressed: () {
            Navigator.of(context).pop(_controller.text);
          },
          child: Text('OK'),
        ),
        MaterialButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: Text('Cancel'),
        ),
      ],
    );
  }
}
